<template>
  <el-dialog
    v-model="dialogFormVisible"
    class="global-dialog"
    :title="title"
    width="600px"
    draggable
    overflow
    @close="close"
  >
    <!-- 内容 start -->
    <div class="mt-[2%] px-3">
      <FormModule @register="formModule.register"/>
    </div>
    <!-- 内容 end -->
    <!-- 操作 -->
    <div class="text-right mt-[2%]">
      <el-button
        color="#1E3485"
        icon="Select"
        size="small"
        @click="onConfirm"
        v-if="dialogType !== 'view'"
        :loading="isLoading"
      >保存</el-button
      >
      <el-button icon="CloseBold" size="small" @click="close"
      >关闭</el-button
      >
    </div>
  </el-dialog>
</template>

<script lang="ts">
import {
  defineComponent, ref, watch, getCurrentInstance, nextTick,
} from 'vue'
import  FormModule, { useForm } from './form.ts'

export default defineComponent({
  name: 'EditDialog',
  components: {
    FormModule,
  },
  expose: ['open', 'close', 'dialogFormVisible'],
  emits: ['confirmRowAdd', 'confirmRowEdit', 'cancel', 'close', 'register'],
  setup(props, { emit }) {

    const formModule = useForm()

    const isLoading = ref(false)
    const dialogFormVisible = ref(false)
    const instance = getCurrentInstance()
    const title = ref('')
    const dialogType = ref('')
    const open = ({ type = 'add', row }) => {
      dialogFormVisible.value = true
      const typeMap = {
        'add': '新建',
        'view': '查看',
        'edit': '编辑',
      }
      dialogType.value = type
      title.value = typeMap[type]
      if(type === 'add' && row.id) {
        title.value = `${typeMap[type]}子项`
      }

      nextTick(() => {
        formModule.resetFields()
        formModule.init(type, row)
      })
    }
    const close = () => {
      dialogFormVisible.value = false
      loading()
      emit('close')
    }

    const loading = () => {
      isLoading.value = false
    }
    const done = () => {
      dialogFormVisible.value = false
      formModule.resetFields()
      loading()
    }
    const onConfirm = () => {
      console.log(isLoading.value)
      if(isLoading.value) return
      isLoading.value = true
      formModule.submitForm().then(({form, row, type}) => {
        if(type === 'add') {
          emit('confirmRowAdd', form, row, done, loading)
          return
        }
        if(type === 'edit') {
          emit('confirmRowEdit', form, row, done, loading)
          return
        }
      }).catch(() => {
        loading()
      })
    }

    emit('register', instance)

    return {
      title,
      dialogFormVisible,
      open,
      close,
      onConfirm,
      formModule,
      dialogType,
      isLoading,
    }
  },
})
</script>
